package com.zh.chat.net.voice;


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class ChatReceive extends Thread {
	// 格式
	private AudioFormat format = new AudioFormat(
			AudioFormat.Encoding.PCM_SIGNED, 44100.0f, 16, 1, 2, 44100.0f,
			false);
	// 管道
	private SourceDataLine line;
	private byte[] data;
	private int port;
	private DatagramSocket socket = null;
	private boolean isRun = false;

	public ChatReceive(int port) {
		try {
			this.port = port;
			socket = new DatagramSocket(port);
			isRun = true;
		} catch (SocketException e1) {
			throw new RuntimeException("尝试语音连接监听"+port+"端口被占用");
		}
		try {
			DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
			line = (SourceDataLine) AudioSystem.getLine(info);
		} catch (LineUnavailableException e) {
			throw new RuntimeException("尝试语音连接，音频输出设备不可用");
		}
	}

	public boolean isRun() {
		return isRun;
	}

	public void setRun(boolean isRun) {
		this.isRun = isRun;
	}

	public void run() {
		System.out.println("receive threading start");
		int length = (int) (format.getFrameSize() * format.getFrameRate() / 2.0f);
		try {
			line.open(format);
			line.start();
			
			System.out.println("start receive");
			while (isRun) {
				// 数组的创建载什么时候，是否影响数据信息？
				data = new byte[length];
				DatagramPacket dp = new DatagramPacket(data, data.length);
				socket.receive(dp);
				line.write(data, 0, data.length);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			socket.close();
		}
	}
}
